
package com.hanlink.dsp.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.ca.model.channel.EqChannel;
import com.hanlink.dsp.util.DspUtil;
import com.hanlink.dsp.util.FreqUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.hanlink.dsp.util.YzToast;
import com.qztech.sdk.model.SettingConstants;
import com.qztech.sdk.ui.widget.ClickableCheckBox;
import com.qztech.utils.YzDebug;


import static com.hanlink.dsp.util.Constants.DIENABLED_ALPHA;
import static com.qztech.sdk.model.SettingConstants.FREQ_MAX;
import static com.qztech.sdk.model.SettingConstants.FREQ_MIN;
import static com.qztech.sdk.model.SettingConstants.Q_MAX;
import static com.qztech.sdk.model.SettingConstants.Q_MIN;

/**
 * Carate By YangZhong
 */
public class EqItemView extends ConstraintLayout implements SeekBar.OnSeekBarChangeListener, View.OnClickListener, View.OnFocusChangeListener {
    //只做绘制用
    private TextView mTvFreq, mTvQ, mTVValueFreq, mTvValueBoost;
    private EqEditText mCCBFreqValue,mTvVqlueQ;
    //只做绘制用结束
    private float mLineWidth = 2f;
    private Paint mPaint;
    private int mLineColor = Color.BLACK;

    private ImageButton mIBFreqAdd, mIBFreqSub, mIBBoostAdd, mIBBoostSub;
    private VerticalSeekBar mFreqSeekBar, mBoostSeekBar;
    private SeekBar mQValueSeekBar;

    private int mPage;
    private int mIndex;
    private boolean isAddSubClickable = true;
    public EqItemView(@NonNull Context context) {
        this(context, null);
    }


    public EqItemView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EqItemView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View.inflate(context, R.layout.layout_eq_item, this);
        mTvFreq = findViewById(R.id.text_freq);
        mTvQ = findViewById(R.id.text_q_text);
        mCCBFreqValue = findViewById(R.id.value_freq);

        //
        mIBFreqAdd = findViewById(R.id.ib_freq_plus);
        mIBFreqSub = findViewById(R.id.ib_freq_sub);
        mIBBoostAdd = findViewById(R.id.ibtn_boost_plus);
        mIBBoostSub = findViewById(R.id.ibtn_boost_sub);
        mIBFreqAdd.setOnClickListener(this);
        mIBFreqSub.setOnClickListener(this);
        mIBBoostAdd.setOnClickListener(this);
        mIBBoostSub.setOnClickListener(this);

        //
        mTVValueFreq = findViewById(R.id.value_freq);
        mTvValueBoost = findViewById(R.id.value_boost);
        mTvVqlueQ = findViewById(R.id.text_q_value);
//        mTvVqlueQ.setOnLongClickListener(this);
//        mTVValueFreq.setOnLongClickListener(this);
        //
        mFreqSeekBar = findViewById(R.id.vSeekbar_freq);
        mBoostSeekBar = findViewById(R.id.vSeekbar_boost);
        mQValueSeekBar = findViewById(R.id.qseekbar);

        mFreqSeekBar.setMax((SettingConstants.FREQ_MAX - FREQ_MIN) * 10);
        mBoostSeekBar.setMax(SettingConstants.GAIN_MAX - SettingConstants.GAIN_MIN);
        mQValueSeekBar.setMax(SettingConstants.Q_MAX - SettingConstants.Q_MIN);


        mFreqSeekBar.setOnSeekBarChangeListener(this);
        mBoostSeekBar.setOnSeekBarChangeListener(this);
        mQValueSeekBar.setOnSeekBarChangeListener(this);

        mPaint = new Paint();
        mPaint.setColor(mLineColor);
        mPaint.setStrokeWidth(mLineWidth);


        mCCBFreqValue.setOnFocusChangeListener(this);
        mTvVqlueQ.setOnFocusChangeListener(this);
        mCCBFreqValue.setValidEditTextListener(()-> {
//            mCCBFreqValue.clearFocus();

        });
        mTvVqlueQ.setValidEditTextListener(()-> {
//            mCCBFreqValue.clearFocus();

        });
    }

    private void validFreqEdittext(){

        int iFreq = 0;
        try {
            final String strFreq = mCCBFreqValue.getText().toString();
            iFreq = Integer.parseInt(strFreq.trim());
        } catch (Exception e) {
            int freq = FreqUtil.parseProgressToFreq(mFreqSeekBar.getProgress());
            mTVValueFreq.setText(String.valueOf(freq));
            YzToast.showShort("Input Error!");
            return;
        }
        if (iFreq < FREQ_MIN || iFreq > FREQ_MAX){
            iFreq = FREQ_MAX;
        }
        int progress = FreqUtil.parseFreqToProgress(iFreq);
        mFreqSeekBar.setProgress(progress);
        if (mOnEqItemViewListener != null){
            mOnEqItemViewListener.onFreqChanged(this, mFreqSeekBar.getProgress());
        }


    }
    private void validQValueEdittext(){

        float fQValue = 0;
        try {
            final String strQValue = mTvVqlueQ.getText().toString();
            fQValue = Float.parseFloat(strQValue.trim());
        } catch (Exception e) {
            mTvVqlueQ.setText(EqChannel.processToQValue(mFreqSeekBar.getProgress()));
            YzToast.showShort("Input Error!");
            return;
        }
        int iQValue = (int) (fQValue*100);
        if (iQValue < Q_MIN || iQValue > Q_MAX){
            iQValue = Q_MIN;
        }
        mQValueSeekBar.setProgress(EqChannel.qToProcess(iQValue));
        if (mOnEqItemViewListener != null){
            mOnEqItemViewListener.onQValueStopTrackingTouch(this);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus)return;
        switch (v.getId()){
            case R.id.value_freq:
                validFreqEdittext();
                break;
            case R.id.text_q_value:
                validQValueEdittext();
                break;
        }
        YzDebug.d("onFocusChange:"+ hasFocus);
    }
    public int getPage() {
        return mPage;
    }

    public int getIndex() {
        return mIndex;
    }

    public void setFreqProgress(int value){
        mFreqSeekBar.setProgress(value);
    }
    public void setBoostProgress(int value){
        mBoostSeekBar.setProgress(value);
    }
    public void setQValueProgress(int value){
        mQValueSeekBar.setProgress(value);
    }

    /**
     * 设置选中后的数值
     */
    public void setValue(float q, int gain, int freq) {
        YzDebug.d("setValue q:"+q +" gain:"+gain+" freq:"+freq);
         mQValueSeekBar.setProgress(EqChannel.qToProcess(q));
        int freqProgress = FreqUtil.parseFreqToProgress(freq);
        if (freqProgress < 0) {
            freqProgress = 0;
        }
        mFreqSeekBar.setProgress(freqProgress);
        mBoostSeekBar.setProgress(gain);
    }
    public void init(int page, int index, int defFreq,OnEqItemViewListener listener) {
        mPage = page;
        mIndex = index;
        int freqProgress = FreqUtil.parseFreqToProgress(defFreq);
        if (freqProgress < 0) {
            freqProgress = 0;
        }
        mFreqSeekBar.setProgress(freqProgress);
        mOnEqItemViewListener = listener;
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        postInvalidate();
    }


    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        final float freqMidY = mTvFreq.getY()+mTvFreq.getHeight()/2f;
        final float valueMideY = mCCBFreqValue.getY()+mCCBFreqValue.getHeight()/2f;
        final float qMideY = mTvQ.getY()+mTvQ.getHeight()/2f;
        canvas.drawLines(new float[] {
                0,freqMidY, mTvFreq.getX(), freqMidY,
                0,valueMideY, mCCBFreqValue.getX(), valueMideY,
                0,qMideY, mTvQ.getX(), qMideY,
                1,freqMidY, 1, qMideY


        }, mPaint);
    }


    private OnEqItemViewListener mOnEqItemViewListener;

    public void setOnEqItemViewListener(OnEqItemViewListener onEqItemViewListener) {
        mOnEqItemViewListener = onEqItemViewListener;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //拖动时为true
        YzDebug.d("onProgressChanged:"+ progress +" " + fromUser);
        switch(seekBar.getId()){
            case R.id.vSeekbar_freq:
                int freq = FreqUtil.parseProgressToFreq(progress);
                mTVValueFreq.setText(String.valueOf(freq));
                if (fromUser && mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onFreqProgressChanged(this,progress, fromUser);
                break;
            case R.id.vSeekbar_boost:
                mTvValueBoost.setText(DspUtil.gainToValue(progress));
                if (fromUser && mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onBoostProgressChanged(this,progress, fromUser);
                break;
            case R.id.qseekbar:
                mTvVqlueQ.setText(EqChannel.processToQValue(progress));
                if (fromUser && mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onQValueProgressChanged(this,progress, fromUser);
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isAddSubClickable = false;
        switch(seekBar.getId()){
            case R.id.vSeekbar_freq:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onFreqStartTrackingTouch(this);
                break;
            case R.id.vSeekbar_boost:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onBoostStartTrackingTouch(this );
                break;
            case R.id.qseekbar:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onQValueStartTrackingTouch(this );
                break;
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        isAddSubClickable = true;
        switch(seekBar.getId()){
            case R.id.vSeekbar_freq:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onFreqStopTrackingTouch(this);
                break;
            case R.id.vSeekbar_boost:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onBoostStopTrackingTouch(this );
                break;
            case R.id.qseekbar:
                if (mOnEqItemViewListener != null)
                    mOnEqItemViewListener.onQValueStopTrackingTouch(this );
                break;
        }
    }

    public boolean onLongClick(View v) {
        switch (v.getId()){
            case R.id.text_q_value:
                ViewUtil.showQValueInputDialog(getContext(),q->{
                    if (q < SettingConstants.Q_MIN){
                        q = SettingConstants.Q_MIN;
                    }else if(q > SettingConstants.Q_MAX){
                        q = SettingConstants.Q_MAX;
                    }

                    int progress = EqChannel.qToProcess(q);
                    mQValueSeekBar.setProgress(progress);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onQValueStopTrackingTouch(this);
                    }
                });
                break;
            case R.id.value_freq:
                ViewUtil.showFreqInputDialog(getContext(),freq->{
                    if (freq < FREQ_MIN){
                        freq = FREQ_MIN;
                    }else if(freq > SettingConstants.FREQ_MAX){
                        freq = SettingConstants.FREQ_MAX;
                    }
                    int progress = FreqUtil.parseFreqToProgress(freq);
                    mFreqSeekBar.setProgress(progress);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onFreqChanged(this, progress);
                    }
                });
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        if (!isAddSubClickable) return;
        int progress ;
        switch (v.getId()){
            case R.id.ib_freq_plus:
                progress = mFreqSeekBar.getProgress();
                int freq = FreqUtil.parseProgressToFreq(progress);
                YzDebug.d("onClick " + progress + " " + mFreqSeekBar.getMax());
                if (freq < SettingConstants.FREQ_MAX){
                    freq++;
                    progress = FreqUtil.parseFreqToProgress(freq);
                    mFreqSeekBar.setProgress(progress);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onFreqChanged(this, mFreqSeekBar.getProgress());
                    }
                }


                break;
            case R.id.ib_freq_sub:
                YzDebug.d("onClick:");
                progress = mFreqSeekBar.getProgress();
                freq = FreqUtil.parseProgressToFreq(progress);
                if (freq > FREQ_MIN){
                    freq--;
                    progress = FreqUtil.parseFreqToProgress(freq);
                    mFreqSeekBar.setProgress(progress);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onFreqChanged(this, mFreqSeekBar.getProgress());
                    }
                }
                break;
            case R.id.ibtn_boost_plus:
                progress = mBoostSeekBar.getProgress();
                if (progress < mBoostSeekBar.getMax()){
                    mBoostSeekBar.setProgress(progress + 1);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onBoostChanged(this, mBoostSeekBar.getProgress());
                    }
                }
                break;
            case R.id.ibtn_boost_sub:
                progress = mBoostSeekBar.getProgress();
                if (progress > 0){
                    mBoostSeekBar.setProgress(progress - 1);
                    if (mOnEqItemViewListener != null){
                        mOnEqItemViewListener.onBoostChanged(this, mBoostSeekBar.getProgress());
                    }
                }
                break;

        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        setChecked(false);
        mIBBoostAdd.setEnabled(enabled);
        mIBBoostSub.setEnabled(enabled);
        mIBFreqAdd.setEnabled(enabled);
        mIBFreqSub.setEnabled(enabled);
        setAlpha(enabled ? 1.0f : DIENABLED_ALPHA);
        mQValueSeekBar.setEnabled(enabled);
        mBoostSeekBar.setEnabled(enabled);
        mFreqSeekBar.setEnabled(enabled);
    }

    public int getQValueProgress(){
        return mQValueSeekBar.getProgress();
    }
    public int getFreqProgress(){
        return mFreqSeekBar.getProgress();
    }
    public int getBoostProgress() {
        return mBoostSeekBar.getProgress();
    }

    public void setChecked(boolean isChecked) {
    }



    public interface OnEqItemViewListener{

        //for add/sub
        void onFreqChanged(EqItemView view, int value);
        void onBoostChanged(EqItemView view, int value);

        //for seekbar freq
        void onFreqProgressChanged(EqItemView view, int progress, boolean fromUser);
        void onFreqStartTrackingTouch(EqItemView view);
        void onFreqStopTrackingTouch(EqItemView view);

        //for seekbar boost
        void onBoostProgressChanged(EqItemView view, int progress, boolean fromUser);
        void onBoostStartTrackingTouch(EqItemView view);
        void onBoostStopTrackingTouch(EqItemView view);

        //for seekbar boost
        void onQValueProgressChanged(EqItemView view, int progress, boolean fromUser);
        void onQValueStartTrackingTouch(EqItemView view);
        void onQValueStopTrackingTouch(EqItemView view);

    }

}
